const dbConfig = require("../utils/dbConfig");
let fs = require('fs')
const jwToken = require('jsonwebtoken')
const secretKey = 'lambyt2021'
function rand(min, max) {
	return Math.floor(Math.random() * (max - min) + min)
}
validatePhoneCode = [];
//判断是否已发送过
let sendCodeP = (phone) => {
	for (var item of validatePhoneCode) {
		if (phone == item.phone) {
			return true
		}
	}
	return false
}
//验证登录
let findCodeAndPhone = (phone, code) => {
	for (var item of validatePhoneCode) {
		if (phone == item.phone && code == item.code) {
			return 'login'
		}
	}
	return 'error'
}

//检测验证码登录是否为第一次登录
let phoneLoginBind = async (phone) => {
	let sql = 'select * from user where username=? or phone=?'
	let sqlArr = [phone, phone]
	let res = await dbConfig.SySqlConnect(sql, sqlArr)
	if (res.length) {
		res[0].userinfo = await getUserInfo(res[0].userID)
		return res
	} else {
		//用户第一次注册绑定表，用户注册
		let res = await regUser(phone)
		//获取用户详情
		res[0].userinfo = await getUserInfo(res[0].userID)
		return res

	}
}
//用户注册
let regUser = async (phone) => {
	let avator = 'http://localhost:3000/uploads/avatar.png'
	let sql = 'insert into user(username,avator,phone,password,nickname,create_time) value (?,?,?,?,?,?)'
	let sqlArr = [phone, avator, phone, phone, phone, (new Date()).valueOf()]
	let res = await dbConfig.SySqlConnect(sql, sqlArr)
	if (res.affectedRows == 1) {
		//执行成功获取用户信息
		//获取用户信息的方法
		let user = await getUser(phone)
		//创建用户副表
		let userinfo = await createUserInfo(user[0].userID)
		if (userinfo.affectedRows == 1) {
			return user
		} else {
			return false
		}
	} else {
		return false
	}
}
//检查用户密码
let checkUserPwd = async (user_id) => {
	let sql = 'select password from user where id=?'
	let sqlArr = [user_id]
	let res = await dbConfig.SySqlConnect(sql, sqlArr)
	console.log(res)
	if (res.length) {
		return res[0].password
	} else {
		return 0
	}
}
//获取用户信息
let getUser = (username) => {
	let sql = 'select * from user where phone = ? or username = ?'
	let sqlArr = [username, username]
	return dbConfig.SySqlConnect(sql, sqlArr)
}
//创建用户副表
let createUserInfo = (user_id) => {
	console.log('创建附表');
	let sql = 'insert into userinfo(userID) values (?)'
	let sqlArr = [user_id]
	return dbConfig.SySqlConnect(sql, sqlArr)
}
//获取用户注册的详情
let getUserInfo = (userID) => {
	let sql = 'select * from userinfo where userID =? '
	let sqlArr = [userID]
	return dbConfig.SySqlConnect(sql, sqlArr)
}
//查看用户详情
let findUserInfo = async (userID) => {
	let sql = 'select * from userinfo where userID=?'
	let sqlArr = [userID]
	let res = await dbConfig.SySqlConnect(sql, sqlArr)
	if (res.length) {
		return true
	}
	return false
}
//修改用户信息详情
let setUserInfo = async (user_id, age, sex, job, path, birthday) => {
	if (findUserInfo(user_id)) {
		let sql = 'update userinfo set age=?,sex=?,job=?,path=?,birthday=? where user_id=?'
		let sqlArr = [age, sex, job, path, birthday, user_id]
		let res = await dbConfig.SySqlConnect(sql, sqlArr)
		if (res.affectedRows == 1) {
			let user = await getUser(user_id)
			let userinfo = await getUserInfo(user_id)
			user[0].userinfo = userinfo[0]
			return user
		} else {
			return false
		}
	} else {
		let sql = 'insert into userinfo(user_id,age,sex,job,path,birthday) values (?,?,?,?,?,?)'
		let sqlArr = [user_id, age, sex, job, path, birthday]
		let res = await dbConfig.SySqlConnect(sql, sqlArr)
		if (res.affectedRows == 1) {
			let user = await getUser(user_id)
			let userinfo = await getUserInfo(user_id)
			user[0].userinfo = userinfo[0]
			return user
		} else {
			return false
		}
	}
}
//修改用户名称
let setUserName = async (user_id, username) => {
	let sql = 'update user set username=? where id=?'
	let sqlArr = [username, user_id]
	let res = await dbConfig.SySqlConnect(sql, sqlArr)
	if (res.affectedRows == 1) {
		return true
	} else {
		return false
	}
}
//模拟验证码发送接口
sendCode = (req, res) => {
	let phone = req.query.phone;
	if (sendCodeP(phone)) {
		res.send({
			'code': 400,
			'msg': '已经发送过验证码，请稍后再发'
		})
	}
	let code = rand(1000, 9999);
	validatePhoneCode.push({
		'phone': phone,
		'code': code
	})
	setTimeout(() => {
		validatePhoneCode.forEach((item, index) => {
			if (item.phone === phone) {
				validatePhoneCode.splice(index, 1)
			}
		})
	}, 60000);
	console.log(validatePhoneCode)
	res.send({
		'code': 200,
		'msg': '发送成功',
		'sms': code
	})
	console.log(code)
}

//验证码登录
codePhoneLogin = async (req, res) => {
	let { phone, code } = req.query;
	let token = jwToken.sign({ username: phone }, secretKey)
	//验证该手机号是否发送过验证码
	if (sendCodeP(phone)) {
		//验证码和手机号是否匹配
		let status = findCodeAndPhone(phone, code)
		if (status == 'login') {
			//登陆成功
			//登陆成功之后的操作
			let user = await phoneLoginBind(phone)
			res.send({
				'code': 200,
				'msg': '登陆成功',
				'data': user[0],
				'token': token
			})
		} else if (status == 'error') {
			res.send({
				'code': 401,
				'msg': '验证码错误'
			})
		}
	} else {
		res.send({
			'code': 400,
			'msg': '未发送验证码'
		})
	}
}

// 密码登录
login = (req, res) => {
	let username = req.query.username,
		password = req.query.password;
	let token = jwToken.sign({ username: username }, secretKey)
	console.log('token', token);
	let sql = 'select * from user where phone=? and password=? or username=? and password=?'
	let sqlArr = [username, password, username, password]
	let callBack = async (err, data) => {
		if (err) {
			console.log(err);
			res.send({
				'code': 400,
				'tip': "出错了"
			})
		} else if (data == "") {
			res.send({
				'code': 400,
				'tip': "用户名或者密码出错",
				'data': []
			})
		} else {
			let user_id = data[0].id;
			let result = await getUserInfo(user_id);
			data[0].userinfo = result[0];
			res.send({
				'code': 200,
				'msg': "登录成功",
				'tip': "登陆成功",
				'data': data[0],
				'token': token
			})
		}
	}
	dbConfig.sqlConnect(sql, sqlArr, callBack)
}
//修改资料
editUserInfo = async (req, res) => {
	let { user_id, username, age, sex, job, path, birthday } = req.query
	let result = await setUserName(user_id, username)
	if (result) {
		let ress = await setUserInfo(user_id, age, sex, job, path, birthday)
		if (ress.length) {
			res.send({
				'code': 200,
				'data': ress[0]
			})
		} else {
			res.send({
				'code': 400,
				'data': "修改失败"
			})
		}
	} else {
		res.send({
			'code': 400,
			'data': "修改失败"
		})
	}
}
//修改密码
setPassword = async (req, res) => {
	let { phone, sms, password } = req.body
	//检查用户密码的方法
	let isCorrect = findCodeAndPhone(phone, sms)
	if (isCorrect === 'login') {
		let sql = 'update user set password=? where phone=?'
		let sqlArr = [password, phone]
		let result = await dbConfig.SySqlConnect(sql, sqlArr)
		if (result.affectedRows == 1) {
			res.send({
				'code': 200,
				'msg': "修改密码成功"
			})
		} else {
			res.send({
				'code': 400,
				'msg': "验证码错误"
			})
		}
	}
}
//新增地址
setAddress = async (req, res) => {
	let { userID,name, phone, address } = req.body
	//检查用户密码的方法
	let sql = 'insert into user_address(userID,name,phone,address) values(?,?,?,?)'
	let sqlArr = [userID, name, phone, address]
	let callBack = (err, data) => {
    if (err) {
      console.log("连接出错了")
    } else {
      res.send({
        'code':200,
        'msg':"新增成功"
      })
    }
  }
  dbConfig.sqlConnect(sql, sqlArr, callBack)

}
//修改头像
editAvator = (req, res) => {
	if (req.file.length === 0) {
		res.render("error", { message: "上传文件不能为空" })
		return
	} else {
		let file = req.file
		console.log(file)
		fs.renameSync('./public/uploads/' + file.filename, './public/uploads/' + file.originalname)
		res.set({
			'content-type': 'application/json;charset=utf-8'
		})
		let { user_id } = req.query
		let imgUrl = 'http://localhost:3000/uploads/' + file.originalname
		let sql = 'update user set avator=? where id=?'
		let sqlArr = [imgUrl, user_id]
		dbConfig.sqlConnect(sql, sqlArr, (err, data) => {
			if (err) {
				console.log(err);
				throw '出错了'
			} else {
				if (data.affectedRows == 1) {
					res.send({
						'code': 200,
						'msg': '修改成功',
						'url': imgUrl
					})
				} else {
					res.send({
						'code': 200,
						'msg': '修改失败',
					})
				}
			}
		})
	}
}
module.exports = {
	sendCode,
	codePhoneLogin,
	login,
	editUserInfo,
	setPassword,
	setAddress,
	editAvator
}